angular.module('login', ['toastr'])
    .controller('loginController',
    ['$scope', '$http', 'toastr',
        function ($scope, $http, toastr) {
            $scope.username = '';
            $scope.pwd = '';
            $scope.remember = true;

            $scope.query = {
                oldPwd: '',
                newPwd: ''
            };
            $scope.newPwdEnsure = '';

            $scope.login = function (event) {
                if (event.keyCode && event.keyCode !== 13) {
                    return;
                }
                if (!$scope.username || !$scope.pwd) {
                    toastr.warning('请输入用户名密码');
                } else {
                    $http.post('/login', {
                        username: $scope.username,
                        pwd: $.md5($scope.pwd),
                        remember: $scope.remember
                    }).success(function (data) {
                        if (data === 'success') {
                            window.location.href = window.location.href;
                        } else {
                            toastr.warning(data.description);
                        }
                    }).error(function () {
                        toastr.error('服务器或网络连接错误');
                    });
                }
            };

            $scope.modifyPwd = function (event) {
                if (event.keyCode && event.keyCode !== 13) {
                    return;
                }
                if (!$scope.query.newPwd || !$scope.query.oldPwd) {
                    toastr.warning('输入不完整');
                    return;
                }
                if ($scope.query.newPwd !== $scope.newPwdEnsure) {
                    toastr.warning('输入密码不一致');
                    return;
                }
                $http.post('/modifyPwd', {
                    oldPwd: $.md5($scope.query.oldPwd),
                    newPwd: $.md5($scope.query.newPwd)
                }).success(function (data) {
                    if (data === 'success') {
                        toastr.success('修改密码成功,2秒后跳转');
                        setTimeout(function () {
                            window.location.href = '/';
                        }, 2000);
                    } else {
                        toastr.warning(data.description);
                    }
                }).error(function () {
                    toastr.error('服务器或网络连接错误');
                });

            }
        }
    ]);